#!/usr/bin/perl
# 
#  Exercise 6.2 
# 
# Write a subroutine to report the percentage of each nucleotide in DNA. You've 
# seen the plus operator +. You will also want to use the divide operator / and the 
# multiply operator *. Count the number of each nucleotide, divide by the total length 
# of the DNA, then multiply by 100 to get the percentage. Your arguments should be 
# the DNA and the nucleotide you want to report on. The int function can be used to 
# discard digits after the decimal point, if needed.
#
# Answer for Exercise 6.2

use strict;
use warnings;

my $DNA = 'ACGTACGTCGTACGTCGTAGCTAGCAGCGTAATAGCGCGCCGCGGATATGG';

my $base = 'A';

print "The percentage of $base in the DNA is ", nucleotide_percentage($DNA, $base), "\n";

exit;

sub nucleotide_percentage {
	my($dna, $nucleotide) = @_;

	my $length = length $dna;

	if($length == 0) { # It's illegal to divide by 0 in most computer languages,
			   # so we check for it before the divide in the next line.
		return 0;
	}

	# To interpolate the variable $nucleotide in the tr/// function, you have
	# to use an "eval" on the pattern match (consult the documentation)
	# $count = (eval "$dna =~ tr/$nucleotide//");
	# Since that's a bit obscure, we'll use a global pattern match instead

	my $count = 0;
	while($dna =~ /$nucleotide/g) { $count++}

	return ( int ( 100 * ( $count / $length) ) );
}
